//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by 汪博文 on 2016/11/15.
//  Copyright © 2016年 Wbw. All rights reserved.
//

import UIKit
//导入模块
import SVProgressHUD
//定义本地路径
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class WBOAuthViewController: UIViewController {
    //定义webView属性
    let webView = UIWebView()
    
    override func loadView() {
        //自定义跟视图
        view = webView
        //制定代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //关闭按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        //输入开发者账号密码 在应用发布时一定要注意注释
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imageName: nil, target: self, action: #selector(fillAccount))
        //设置背景颜色 使用手写代码创建的控制器的背景颜色是透明的
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //请求授权页面
        loadOauthPage()
        //在本类中无法调用分类中的私有方法
    }
    
    private func loadOauthPage() {
        //加载微薄授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
        
    }
    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = 'wbw14@163.com',document.getElementById('passwd').value = 'wbw2yn1314'"
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

//将代理方法,抽取到分类中实现,将模块的功能单独独立出来更加好维护
extension WBOAuthViewController :UIWebViewDelegate {
    //MARK: 实现协议代理方法 让网络访问时出现加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //在页面将要关闭的时候 dismiss掉指示器
    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
    }
    //MARK: 拿到code
    //一般协议方法为bool类型,如果返回true,就可以正常工作否则就不能够正常工作
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //绝对路径 防止是相对路径
        let urlString = request.url?.absoluteString ?? ""
        //判断urlString 中是否包含了特殊的标记,如果包含就可以截取code
        let flag = "code="
        if urlString.contains("code=") {
            //能够根据"code="截取code=
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            //获取了code之后就应该使用code 获取用户的token(访问接口的唯一标识)
            //如果获取了code之后就应该 return false 不加载页面
            //在这里做网络请求,做完网络请求后不加载页面了
            WBUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSuccessed: Bool) -> () in
                if !isSuccessed {
                    SVProgressHUD.showError(withStatus: errorString)
                    return
                }
                //请求成功
                print("请求成功")
                //切换根视图控制器 要在AppDelegate里用通知切换
                //UIApplication.shared.keyWindow?.rootViewController = WBWeicomeViewController()
                //object:表示哪个对象发的通知,通常用来传参数
                NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: "Welcome")
                
            })
            return false
        }
        
        return true
    }
}
//这些代码被封装到WBUserAccountModel中
/*
    //获取用户token
    private func loadAccessToken(code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                return
            }
            //请求成功
            //使用access_token 和 uid 来请求用户接口
            //获取用户信息
            self.loadUserInfo(dict: responseObject as! [String : Any])
            
        }
    }
    private func loadUserInfo(dict: [String : Any]) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        //oc中的字典不能存放nil
        let parameters = ["access_token" : token,
                          "uid" : uid]
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "世界上最遥远的距离是没有网络")
                return
            }
            //print(responseObject)
            //将用户信息存储在本地
            //要把用户的access_token 也存储下来 但是responseObject里面没有
            //所以讲授权之后得到的字典和用户信息字典合并之后再存储
            var userInfoDict = responseObject as! [String : Any]
            for (key,value) in dict {
                userInfoDict[key] = value
            }
            //需要将userInfoDict转换模型对象
            //用归档的方式存储自定义模型对象
            //字典转模型
            let userAccount = WBUserAccount(dict : userInfoDict)
//            print(userAccount)
            self.saveUserAccount(userAccount: userAccount)
            
            let cacheAccount = self.loadUserAccount()
            print(cacheAccount)
        }
    }
    //存储用户模型对象的方法 用归档的方法
    private func saveUserAccount(userAccount: WBUserAccount) {
        //存储在沙盒的document或者library,temp路径不会备份
        //拼接文件路径的方法string 没有 需要转换为NSString
        //使用as的前提:被转换的类型不能够为可选类型对象
//        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
        //存储自定义对象,自定义对象必须遵守 NSCoding协议 实现协议方法
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
//      本地路径path: /Users/wangbowen/Library/Developer/CoreSimulator/Devices/0C4280C4-8457-4091-A2A8-C7D308D35DD1/data/Containers/Data/Application/14691982-6B92-43C3-98BC-CB93E4568915/Documents/account.plist
    }
    //读取本地数据
    private func loadUserAccount() -> WBUserAccount? {
        //调用解档的方法
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        if let userAccount = account as? WBUserAccount {
            return userAccount
        }
        return nil
    }
*/




















